//
//  LoginViewController.m
//  LiveEducation
//
//  Created by Liu,Qingcan on 2017/4/12.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "LoginViewController.h"
#import "Masonry.h"
#import "RegistersViewController.h"
#import "UserModel.h"
#import "UserInfoApi.h"
#import "LoginApi.h"
#import "RegisterApi.h"
#import "UserInfoApi.h"

#define NavGationBar 64

@interface LoginViewController ()<UITextFieldDelegate>


/**header 视图*/
@property (nonatomic,strong)UIImageView *topicImageView;

/**登录栏*/
@property (nonatomic,strong)UITextField *usernameField;
@property (nonatomic,strong)UITextField *passwordField;
@property (nonatomic,strong)UIButton *loginButton;
@property (nonatomic,strong)UIButton *questionButton;
@property (nonatomic,strong)UIButton *registerButton;

/**辅助登录栏*/
@property (nonatomic,strong)UILabel *clipsLabel;

/**footer 视图*/
@property (nonatomic,strong)UIImageView *footerImageView;

@end

@implementation LoginViewController

#pragma mark -life circle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
    [self addNotification];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:YES];
//    [self.navigationController setNavigationBarHidden:YES];
//}
//
//- (void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:YES];
//    [self.navigationController setNavigationBarHidden:NO];
//}


- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
//    [self.view layoutSubviews]
    [_topicImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(20 + NavGationBar);
//        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(20, 20, <#CGFloat bottom#>, <#CGFloat right#>))
        make.left.equalTo(self.view).with.offset(80);
        make.right.equalTo(self.view).with.offset(-80);
        make.height.mas_equalTo(80);
    }];
    
    [_footerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-80);
        make.left.equalTo(self.view).with.offset(10);
        make.right.equalTo(self.view).with.offset(-10);
        make.height.mas_equalTo(20);
    }];
    
    [_usernameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY).with.offset(-60);
        make.width.equalTo(self.view.mas_width).with.offset(-60);
        make.height.mas_equalTo(35);
    }];
    
    [_passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_usernameField.mas_bottom).with.offset(2);
        make.centerX.equalTo(_usernameField.mas_centerX);
        make.width.equalTo(_usernameField.mas_width);
        make.height.equalTo(_usernameField.mas_height);
    }];
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordField.mas_bottom).with.offset(10);
        make.centerX.equalTo(_passwordField.mas_centerX);
        make.width.equalTo(_passwordField.mas_width).offset(-28);
        make.height.equalTo(_passwordField.mas_height).offset(1);
    }];
    
    [_clipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginButton.mas_bottom).with.offset(10);
        make.centerX.equalTo(_loginButton.mas_centerX);
        make.width.mas_equalTo(0.7f);
        make.height.mas_equalTo(20.f);
    }];

    
    
    [_questionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_clipsLabel.mas_centerY);
//        make.centerX.equalTo(_clipsLabel.mas_centerX).offset(_loginButton.mas_width);
//        make.width.equalTo(_clipsLabel.mas_width);
        
        make.height.equalTo(_clipsLabel.mas_height).offset(-1);
        make.right.equalTo(_clipsLabel.mas_left).offset(-15);
//        make.left.equalTo(_loginButton.mas_left).offset(15);
        make.width.mas_equalTo(80);
    }];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_clipsLabel.mas_centerY);
        make.height.equalTo(_questionButton.mas_height);
        make.left.equalTo(_clipsLabel.mas_right).offset(15);
        make.width.equalTo(_questionButton.mas_width).offset(-40);
    }];
    

    
    
    
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (_passwordField.text.length > 0 && _usernameField.text.length > 0) {
        NSString *username = _usernameField.text;
        NSString *password = _passwordField.text;
        
        LoginApi *api = [[LoginApi alloc]initWithUserName:username userPwd:password];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            NSNumber *status = dict[@"statusCode"];
            if (status.integerValue == 1) {
                NSLog(@"登录成功");
                //插入login状态
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setBool:YES forKey:@"user_login_status"];
               
           
                NSDictionary *dicts = dict[@"data"];
                NSLog(@"获取用户信息成功");
                UserModel *userDao = [[UserModel alloc]init];
                LEUserItem *item = [LEUserItem yy_modelWithJSON:dicts];
                [userDao insertUserData:item];
                //插入用户id
                [defaults setInteger:item.nid forKey:@"userId"];
                
                
                
                //////这里需要使用yymodel转一下
//                for(NSDictionary *dc in dicts){
//                    LEUserItem *item = [LEUserItem yy_modelWithJSON:dc];
//                    [userDao insertUserData:item];
//                }
                
                
                
#warning 这里需要使用yymodel转一下
//                UserInfoApi *infoApi = [[UserInfoApi alloc]initWithUserId:userId.integerValue];
//                [infoApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//                    NSDictionary *dict = request.responseJSONObject;
//                    NSNumber *status = dict[@"statusCode"];
//                    if (status.integerValue == 1) {
//                        NSLog(@"获取用户信息成功");
//                    User *user = dict[@"data"];//////这里需要使用yymodel转一下
//                    UserModel *userDao = [[UserModel alloc]init];
//                    User *item = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:userDao.persistence.currentContext];
//                    item = user;
//                    [userDao insertUserData:item];
//                    }
//                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//                    
//                }];
                
                
                
                
                
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"YES！" message:@"登录成功" preferredStyle:UIAlertControllerStyleAlert];
                
                    __weak typeof(self) wself = self;
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                        [wself popoverPresentationController];
                    [wself.navigationController popViewControllerAnimated:YES];
                }];
                [alertVC addAction:okAction];
                
                [self presentViewController:alertVC animated:YES completion:nil];
            }else{
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Failed！" message:@"！登录失败了~" preferredStyle:UIAlertControllerStyleAlert];
                
                __weak typeof(self) wself = self;
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    //                        [wself popoverPresentationController];
                    [wself.navigationController popViewControllerAnimated:YES];
                }];
                [alertVC addAction:okAction];
                
                [self presentViewController:alertVC animated:YES completion:nil];
                NSLog(@"登录失败");
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
        
        
    }
    
    if (textField.tag == 100) {
        
    }else if(textField.tag == 101){
        
    }
    
  
    
    
    
        
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return [textField resignFirstResponder];
}



#pragma mark event response
- (void)didClickedLoginBtn:(UIButton *)sender{
    NSLog(@"click login");
    [_passwordField resignFirstResponder];
    [_usernameField resignFirstResponder];
    
}

- (void)didClickedRegiserBtn:(UIButton *)sender{
//    NSLog(@"click register");
    [_passwordField resignFirstResponder];
    [_usernameField resignFirstResponder];

    
    RegistersViewController *registerVC = [[RegistersViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
    
}

- (void)didClickedQuestionBtn:(UIButton *)sender{

    //attribute string
    UIFont *font1 = [UIFont fontWithName:@"HelveticaNeue-Medium" size:17.0f];
    UIFont *font2 = [UIFont fontWithName:@"HelveticaNeue-Light" size:13.0f];
    UIColor *color = [UIColor colorWithRed:233/255.f green:96/255.f blue:54/255.f alpha:1];
    NSDictionary *importDict = @{NSForegroundColorAttributeName:color,
                                 NSFontAttributeName:font1
                                 };
    NSDictionary *normalDict = @{NSForegroundColorAttributeName:[UIColor blackColor],
                                 NSFontAttributeName:font2
                                 };
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]init];
    [attrStr appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n 请使用 " attributes:normalDict]];
    [attrStr appendAttributedString:[[NSAttributedString alloc]initWithString:@"\"中公教育\"" attributes:importDict]];
    [attrStr appendAttributedString:[[NSAttributedString alloc]initWithString:@" 平台的密码和帐号" attributes:normalDict]];

    NSString* string = attrStr.string;
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"说明！" message:string preferredStyle:UIAlertControllerStyleAlert];
    
#warning 私有api,审核通不过
    [alertVC setValue:attrStr forKey:@"attributedMessage"];

    
//    __weak typeof(self) wself = self;
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        [wself popoverPresentationController];
    }];
    [alertVC addAction:okAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}




- (void)keyboardChanged:(NSNotification *)notification{
    CGRect keyboardFram = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    float duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGFloat viewH = [UIScreen mainScreen].bounds.size.height;
    
   
    [UIView animateWithDuration:duration animations:^{
        
        if (viewH == keyboardFram.origin.y) {
            self.view.transform = CGAffineTransformMakeTranslation(0, 0);
        }else{
            self.view.transform = CGAffineTransformMakeTranslation(0, keyboardFram.origin.y +  keyboardFram.size.height*0.6 - viewH);
        }
        
    }];
    
    //2.
//    [self.view mas_updateConstraints:^(MASConstraintMaker *make)
//     {
//         make.centerY.equalTo(self.mas_centerY).with.offset(-height*0.5);
//     }];

}



- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
#pragma mark private
- (void)setupViews{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topicImageView];
    [self.view addSubview:self.usernameField];
    [self.view addSubview:self.passwordField];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.questionButton];
    [self.view addSubview:self.registerButton];
    [self.view addSubview:self.footerImageView];
    [self.view addSubview:self.clipsLabel];
    
}

- (void)addNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardDidHideNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


#pragma mark getter & setter
- (UITextField *)usernameField{
    if (!_usernameField) {
        _usernameField = [[UITextField alloc]init];
        _usernameField.placeholder = @"输入用户名/手机号/邮箱";
        _usernameField.font = [UIFont systemFontOfSize:13.f];
        _usernameField.textAlignment = NSTextAlignmentLeft;
//        _usernameField.backgroundColor = [UIColor purpleColor];
        
        _usernameField.borderStyle = UITextBorderStyleRoundedRect;
        _usernameField.keyboardType = UIKeyboardTypeDefault;
        _usernameField.returnKeyType = UIReturnKeyNext;
        
        _usernameField.tag = 100;
        _usernameField.delegate = self;
        
        
    }
    return _usernameField;
}

- (UITextField *)passwordField{
    if (!_passwordField) {
        _passwordField = [[UITextField alloc]init];
        _passwordField.placeholder = @"输入密码";
        _passwordField.font = [UIFont systemFontOfSize:13.f];
        _passwordField.textAlignment = NSTextAlignmentLeft;
//        _passwordField.backgroundColor = [UIColor purpleColor];
        
        _passwordField.borderStyle = UITextBorderStyleRoundedRect;
        _passwordField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _passwordField.returnKeyType = UIReturnKeyGo;
        _passwordField.secureTextEntry = YES;
        
        _passwordField.tag = 101;
        _passwordField.delegate = self;
    }
    return _passwordField;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//        _loginButton.titleLabel.text = @"登录"; ///这个不行
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        _loginButton.tintColor = [UIColor whiteColor];
        _loginButton.backgroundColor = [UIColor orangeColor];
        
        ///背景图片
//        [_loginButton setBackgroundImage:[UIImage imageNamed:@"login_normal"] forState:UIControlStateNormal];
//        [_loginButton setBackgroundImage:[UIImage imageNamed:@"naruto"] forState:UIControlStateHighlighted];
        
        
        [_loginButton addTarget:self action:@selector(didClickedLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (UIButton *)registerButton{
    if (!_registerButton) {
        _registerButton = [[UIButton alloc]init];
//        _registerButton.titleLabel.text = @"注册";
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
         [_registerButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        
        _registerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//        _registerButton.contentMode = UIViewContentModeLeft;
//        _registerButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        
        _registerButton.titleLabel.tintColor = [UIColor orangeColor];
        _registerButton.titleLabel.font = [UIFont systemFontOfSize:11.f];
//        _registerButton.backgroundColor = [UIColor redColor];
        
        [_registerButton addTarget:self action:@selector(didClickedRegiserBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}

- (UIButton *)questionButton{
    if(!_questionButton){
        _questionButton = [[UIButton alloc]init];
//        _questionButton.titleLabel.text = @"登录遇到问题?";
        [_questionButton setTitle:@"登录遇到问题?" forState:UIControlStateNormal];
        [_questionButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        _questionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//        _questionButton.contentMode = UIViewContentModeRight;
        
        
        _questionButton.titleLabel.font = [UIFont systemFontOfSize:11.f];
        _questionButton.titleLabel.tintColor = [UIColor orangeColor];
//        _questionButton.backgroundColor = [UIColor redColor];
        
        
        [_questionButton addTarget:self action:@selector(didClickedQuestionBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _questionButton;
}


- (UIImageView *)topicImageView{
    if (!_topicImageView) {
        _topicImageView = [[UIImageView alloc]init];
        [_topicImageView setImage:[UIImage imageNamed:@"headlogo"]];
        _topicImageView.contentMode = UIViewContentModeScaleToFill;
//        _topicImageView.backgroundColor = [UIColor orangeColor];
    }
    return _topicImageView;
}


- (UIImageView *)footerImageView{
    if (!_footerImageView) {
        _footerImageView = [[UIImageView alloc]init];
        [_footerImageView setImage:[UIImage imageNamed:@"footer_logo"]];
        _footerImageView.contentMode = UIViewContentModeScaleToFill;
//        _footerImageView.backgroundColor = [UIColor yellowColor];
    }
    return _footerImageView;
}



- (UILabel *)clipsLabel{
    if (!_clipsLabel) {
        _clipsLabel = [[UILabel alloc]init];
        _clipsLabel.backgroundColor = [UIColor grayColor];
        _clipsLabel.userInteractionEnabled = NO;
        
    }
    return _clipsLabel;
}

@end
